package com.taijia.chapter5;

import java.util.Random;

import com.alibaba.fastjson.JSON;

public class NumberSort {

	/**
	 * 选择排序-交换值
	 * 
	 * @param is
	 * @return
	 */
	private static int[] simpleSort(int[] is) {
		long start = System.currentTimeMillis();
		for (int i = 0; i < is.length; i++) {
			for (int j = i + 1; j < is.length; j++) {
				if (is[i] > is[j]) {
					int tmp = is[i];
					is[i] = is[j];
					is[j] = tmp;
				}
				continue;
			}
		}
		long end = System.currentTimeMillis();
		System.out.println("time:" + (end - start));
		return is;
	}

	/**
	 * 选择排序-交换键
	 * 
	 * @param is
	 * @return
	 */
	private static int[] selectSort(int[] is) {
		long start = System.currentTimeMillis();
		int i, j, k, tmp;
		for (i = 0; i < is.length; i++) {
			k = i;
			for (j = k + 1; j < is.length; j++) {
				if (is[k] > is[j])
					k = j;
				continue;
			}
			if (i == k)
				continue;
			tmp = is[i];
			is[i] = is[k];
			is[k] = tmp;
		}
		long end = System.currentTimeMillis();
		System.out.println("time:" + (end - start));
		return is;
	}

	/**
	 * 冒泡排序
	 * @param is
	 * @return
	 */
	private static int[] bubbleSort(int[] is) {
		long start = System.currentTimeMillis();
		int len = is.length;
		for (int i = len - 1; i > 0; i--) {
			for (int j = 0; j < i; j++) {
				if (is[j] > is[j + 1]) {
					int tmp = is[j];
					is[j] = is[j + 1];
					is[j + 1] = tmp;
				}
			}
		}
		long end = System.currentTimeMillis();
		System.out.println("time:" + (end - start));
		return is;
	}

	public static void main(String[] args) {
		final int SIZE = 10000;
		int[] is = new int[SIZE];
		for (int i = 0; i < is.length; i++) {
			is[i] = new Random().nextInt(SIZE);
		}
		int[] simpleSortArr = is;// {9,5,8,3,1,4,6,7,2};
		int[] selectSortArr = simpleSortArr.clone();
		int[] bubbleSortArr = selectSortArr.clone();
		simpleSort(simpleSortArr);
//		System.out.println(JSON.toJSONString(simpleSortArr));
		selectSort(selectSortArr);
//		System.out.println(JSON.toJSONString(selectSortArr));
		bubbleSort(bubbleSortArr);
//		System.out.println(JSON.toJSONString(selectSortArr));
	}
}
